using System;
using System.Web;
using System.IO;
using System.Xml.Serialization;
using System.Web.Caching;

namespace MyWebPagesStarterKit
{
    //Copy of persistable, but all caching are removed to get current values.
    public abstract class DataManager<T>
    {
        private String _path;
        protected T _data;

        public DataManager()
        {
            _data = (T)Activator.CreateInstance(typeof(T));
        }

     
        protected void LoadData()
        {
            _path = HttpContext.Current.Server.MapPath(GetDataFilename());

            if (!File.Exists(_path))
                SaveData();

            lock (_path)
            {
                using (FileStream reader = File.Open(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    _data = (T)serializer.Deserialize(reader);
                }
            }
        }

        public void SaveData()
        {
            _path = HttpContext.Current.Server.MapPath(GetDataFilename());
            lock (_path)
            {
                if (!Directory.Exists(Path.GetDirectoryName(_path)))
                    Directory.CreateDirectory(Path.GetDirectoryName(_path));


                using (FileStream writer = File.Create(_path))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(writer, _data);
                }
            }
        }


        public virtual bool Delete()
        {
            bool success = true;

            if (File.Exists(_path))
            {
                lock (_path)
                {
                    try
                    {
                        File.Delete(_path);
                      
                    }
                    catch { success = false; }
                }
            }
            return success;
        }

        protected abstract string GetDataFilename();
    }
}
